package com.shop.shopmall.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.shop.shopmall.dto.User;
import com.shop.shopmall.pojo.GoodsAttrValue;
import com.shop.shopmall.pojo.GoodsInfo;
import com.shop.shopmall.service.GoodsAttrValueService;
import com.shop.shopmall.service.GoodsInfoService;
import com.shop.shopmall.vo.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品管理
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    GoodsInfoService goodsInfoService;

    @Autowired
    GoodsAttrValueService goodsAttrValueService;

    @Autowired
    ElasticsearchClient client;

    /**
     * 分页条件查询
     *
     * @param goodsInfo
     * @return
     */
    @PostMapping("/pageList")
    public Result<?> getGoodsList(@RequestBody GoodsInfo goodsInfo) {
        return Result.success(goodsInfoService.getGoodsInfoList(goodsInfo));
    }

    @GetMapping("/goodsTotal")
    public Result<?> getGoodsTotal() {
        return Result.success(goodsInfoService.getGoodsTotal());
    }

    /**
     * 新增或修改（商品信息表）
     *
     * @param goodsInfo
     * @return
     */
    @PostMapping("/addGoods")
    public Result<?> addGoods(@RequestBody GoodsInfo goodsInfo) {
        // 处理分类ID
        if (null != goodsInfo.getClassifyIds()) {
            StringBuilder sb = new StringBuilder();
            for (Integer classifyId : goodsInfo.getClassifyIds()) {
                sb.append(classifyId).append(",");
            }
            goodsInfo.setClassify(sb.substring(0, sb.length() - 1));
        }
        goodsInfoService.saveOrUpdate(goodsInfo);
        try {
            // 连接ES，将数据同步到ES
            BooleanResponse booleanResponse = client.indices().exists(e -> e.index("goods"));
            if (!booleanResponse.value()) {
                // 索引不存在时，才创建索引
                client.indices().create(c -> c.index("goods"));
            }
            // 添加文档
            client.index(i -> i.index("goods").id(String.valueOf(goodsInfo.getId())).document(goodsInfo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(goodsInfo.getId());
    }

    /**
     * 新增或修改（商品属性表）
     *
     * @param goodsAttrValue
     * @return
     */
    @PostMapping("/addGoodsAttr")
    public Result<?> addGoodsAttrValue(@RequestBody GoodsAttrValue goodsAttrValue) {
        boolean b = goodsAttrValueService.saveOrUpdate(goodsAttrValue);
        return Result.success(b);
    }

    /**
     * 修改状态
     *
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/status/{id}/{status}")
    public Result<?> update(@PathVariable Integer id, @PathVariable String status) {
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setId(id);
        goodsInfo.setStatus(status);
        return Result.success(goodsInfoService.saveOrUpdate(goodsInfo));
    }

    /**
     * 添加回收站
     *
     * @param id
     * @return
     */
    @PutMapping("/recycle/{id}")
    public Result<?> recycle(@PathVariable Integer id) {
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setId(id);
        goodsInfo.setStatus("0");
        goodsInfo.setIsRecycle("1");
        return Result.success(goodsInfoService.saveOrUpdate(goodsInfo));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteGoods(@PathVariable int id) {
        return Result.success(goodsInfoService.removeById(id));
    }

    /**
     * 导出Excel
     *
     * @return
     */
    @PostMapping("/downloadExcel")
    public void downloadExcel(HttpServletResponse response) {
        try {
            // 生成模拟数据
            List<User> users = new ArrayList<>();
            users.add(new User("张三", 25));
            users.add(new User("李四", 30));
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 设置编码格式
            response.setCharacterEncoding("utf-8");
            // 设置文件名
            String fileName = URLEncoder.encode("商品信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 写入Excel
            EasyExcel.write(response.getOutputStream(), User.class) //（输出流， 文件头）
                    .excelType(ExcelTypeEnum.XLSX)
                    .autoCloseStream(true)
                    .sheet("商品信息") //第一个sheet的名
                    .doWrite(users); //写入数据
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
